<?php

namespace app\admin\controller;

use app\models\{Admin as model, AdminLogin, Region};
use app\validate\Admin as Validate;
use think\Db;
use think\facade\Debug;

class Admin extends Base
{

    public function index()
    {
        $admin = $this->request->admin;
        $results = (new model())->where('id', '<>', $admin['id'])->order('id desc');
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $results = $results->where('nickname|username', 'like', '%' . $data['title'] . '%');
        }
        switch ($admin['type']) {
            case '2':
                //获取所有合格会员
                $alist = (new model())->where(['type' => [3, 4]])->select();
                //查询管辖范围内的
                $admin_arr = [];
                foreach ($alist as $alists) {
                    $row['city'] = array_filter(explode(',', $alists['city']));
                    //取交集
                    $arr = array_intersect($admin['city'], $row['city']);
                    //如果管理城市一样 则可以管理
                    if (count($arr) == count($row['city'])) {
                        $admin_arr[] = $alists['id'];
                    }
                }
                $results = $results->where(['id' => $admin_arr]);
                break;
            case '3':
                //获取所有合格会员
                $alist = (new model())->where(['type' => 4])->select();
                //查询管辖范围内的
                $admin_arr = [];
                foreach ($alist as $alists) {
                    $row['area'] = array_filter(explode(',', $alists['area']));
                    //取交集
                    $arr = array_intersect($admin['area'], $row['area']);
                    //如果管理城市一样 则可以管理
                    if (count($arr) == count($row['area'])) {
                        $admin_arr[] = $alists['id'];
                    }
                }
                $results = $results->where(['id' => $admin_arr]);
                break;
            case '4':
                $results = $results->where(['id' => []]);
                break;
            default:
                break;
        }
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        if (!empty($data['type'])) {
            $results = $results->where('type', $data['type']);
        }
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $results = $results->where(['province' => $data['province']]);
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
        }

        $results = $results->paginate(10)->each(function ($row) {
            $row['city'] = array_filter(explode(',', $row['city']));
            $row['area'] = array_filter(explode(',', $row['area']));
            $row['street'] = array_filter(explode(',', $row['street']));
            $row['province_list'] = [];
            $row['city_list'] = [];
            $row['area_list'] = [];
            $row['street_list'] = [];
            $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->select();
            $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->select();
            $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->select();
            $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->select();
        });
        return view(null, [
            'list' => $results,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street
        ]);
    }

    public function input()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('data');
            $validate = new Validate();
            if (!$validate->scene('add')->check($data) && empty($data['id'])) {
                return json(['status' => 1, 'msg' => $validate->getError()]);
            }
            if (!$validate->scene('edit')->check($data) && !empty($data['id'])) {
                return json(['status' => 1, 'msg' => $validate->getError()]);
            }
            $haveadmin = (new model())->where('username', $data['username'])->find();
            if (!empty($haveadmin) && $haveadmin['id'] != $data['id']) {
                return json(['status' => 1, 'msg' => '账号名称已被使用']);
            }
            $admin = $this->request->admin;
            if ($admin['type'] >= $data['type'] && $admin['type'] != 1) {
                return json(['status' => 1, 'msg' => '管理员类型权限不足,请选择其它下级类型']);
            }
            switch ($data['type']) {
                case '1':
                    $data['province'] = 0;
                    $data['city'] = [];
                    $data['area'] = [];
                    $data['street'] = [];
                    break;
                case '2':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    $data['area'] = [];
                    $data['street'] = [];
                    break;
                case '3':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    $data['street'] = [];
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['status' => 1, 'msg' => '请选择街道']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '管理员类型错误']);
                    break;
            }
            //管理员权限判断
            switch ($admin['type']) {
                case '1':
                    break;
                case '2':
                    //验证城市是否在范围内
                    foreach ($data['area'] as $area) {
                        //查找父级城市
                        $areas = (new Region())->where(['level' => 3, 'area_code' => $area])->find();
                        if (empty($areas)) {
                            return json(['status' => 1, 'msg' => '区域信息不存在']);
                        }
                        //查找父级
                        $areas_top = (new Region())->where(['level' => 2, 'id' => $areas['parent_id']])->find();
                        if (empty($areas_top)) {
                            return json(['status' => 1, 'msg' => '城市信息不存在']);
                        }
                        if (!in_array($areas_top['area_code'], $admin['city'])) {
                            return json(['status' => 1, 'msg' => $areas['name'] . '属于' . $areas_top['name'] . '不在您的管理范围内']);
                        }
                    }
                    break;
                case '3':
                    //验证城市是否在范围内
                    foreach ($data['street'] as $street) {
                        //查找父级城市
                        $streets = (new Region())->where(['level' => 4, 'id' => $street])->find();
                        if (empty($streets)) {
                            return json(['status' => 1, 'msg' => '街道信息不存在']);
                        }
                        //查找父级
                        $streets_top = (new Region())->where(['level' => 3, 'id' => $streets['parent_id']])->find();
                        if (!in_array($streets_top['area_code'], $admin['area'])) {
                            return json(['status' => 1, 'msg' => $streets['name'] . '属于' . $streets_top['name'] . '不在您的管理范围内']);
                        }
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '管理员类型错误']);
                    break;
            }
            $data['role'] = implode(',', $data['role'] ?? []);
            $data['city'] = implode(',', $data['city'] ?? []);
            $data['area'] = implode(',', $data['area'] ?? []);
            $data['street'] = implode(',', $data['street'] ?? []);
            if (isset($data['password']) && $data['password']) {
                $entry = $this->get_rand_str();
                $data['entry'] = $entry;
                $data['password'] = md5(md5($data['password']) . md5($entry));
            } else {
                unset($data['password']);
            }
            if ($data['id'] > 0) {
                $res = (new model())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new model())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new model())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            if (!empty($row)) {
                $row['role'] = array_filter(explode(',', $row['role']));
                $row['city'] = array_filter(explode(',', $row['city']));
                $row['area'] = array_filter(explode(',', $row['area']));
                $row['street'] = array_filter(explode(',', $row['street']));
                $parent = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->find();
                $city = (new Region())->where(['level' => 2, 'parent_id' => $parent['id']])->select();
                foreach ($row['area'] as $areas) {
                    $areag = (new Region())->where(['level' => 3, 'area_code' => $areas])->find();
                    $parent_c =  (new Region())->where(['level' => 2, 'id' => $areag['parent_id']])->find();
                    //查找父级
                    if (empty($area[$parent_c['id']])) {
                        $area[$parent_c['id']]['area_code'] = $parent_c['area_code'];
                        $area[$parent_c['id']]['name'] = $parent_c['name'];
                        $area[$parent_c['id']]['lists'] = (new Region())->where(['level' => 3, 'parent_id' => $parent_c['id']])->select();
                    }
                }
                foreach ($row['street'] as $streets) {
                    $streetg = (new Region())->where(['level' => 4, 'id' => $streets])->find();
                    $parent_s =  (new Region())->where(['level' => 3, 'id' => $streetg['parent_id']])->find();
                    //查找父级
                    if (!empty($parent_s) && empty($area[$parent_s['id']])) {
                        $street[$parent_s['id']]['nname'] = (new Region())->where(['level' => 2, 'id' => $parent_s['parent_id']])->value('name');
                        $street[$parent_s['id']]['area_code'] = $parent_s['area_code'];
                        $street[$parent_s['id']]['name'] = $parent_s['name'];
                        $street[$parent_s['id']]['lists'] = (new Region())->where(['level' => 4, 'parent_id' => $parent_s['id']])->select();
                    }
                }
            } else {
                $data['role'] = [];
            }
            return view('', [
                'data' => $row,
                'role' => $this->request->admin['role'],
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street

            ]);
        }
    }

    public function del()
    {
        $admin_id =  $this->request->get('id');
        $admin = (new model())->where('id', $admin_id)->find();
        if ($admin['is_default'] == 1) {
            return json(['status' => 1, 'msg' => '超级管理员不允许删除']);
        }
        $res = (new model())->where('id', $admin_id)->delete();
        if ($res) {
            return json(['status' => 0, 'msg' => '删除成功']);
        }
        return json(['status' => 1, 'msg' => '操作失败']);
    }

    //登录日志
    public function login_log()
    {
        $data = input('param.');
        $list = (new AdminLogin())->where('uid', $this->request->admin['id'])->order('id DESC');
        if (isset($data['username']) && $data['username']) {
            $list->where('username', $data['username']);
        }
        $lists = $list->paginate(10, false, ['query' => $this->request->param()]);
        return view('', ['list' => $lists]);
    }
}
